<template>
	<view>
		<my-chat ref="myChatRef" :chatList="chatList" :imgList="chatImgs" :msgObjectData="msgObjectData"
			:isSendMsg="isShowSend" :sendTitle="sendTitle" @sendMsg="sendMsg" @gotoUserSet="gotoUserSet"
			@showRedPkg="showRedPkg" @closeUserMsg="closeUserMsg" @withdrawUserMsg="withdrawUserMsg"
			@getChatListByPage="getChatListByPage" @handleAudio="handleAudio"
			@changeMsgListLeng="changeMsgListLeng"></my-chat>

		<!-- 红包信息 -->
		<chat-redpkg-animation @closeHbFun="closeHbFun" :showHbMsg="showHbMsg" :rbagmodelshow="isShowHb"
			@openHbFun="openHbFun" :openbrnanimation="openbrnanimation" :openrbagmodelshow="openrbagmodelshow"
			@gotoDetail="gotoDetail"></chat-redpkg-animation>
	</view>
</template>

<script>
	//1，引入核心组件
	import myChat from '@/components/content/my-new-chat/my-chat.vue'
	import chatRedpkgAnimation from '@/components/content/my-chat/common/chat-redpkg/redpkg-animation.vue'

	//2，引入vuex
	import {
		mapState,
		mapMutations,
		mapActions,
		mapGetters
	} from 'vuex'

	//3，引入工具类
	import {
		getNowTime
	} from '@/utils/time/time.js'

	//4，引入实体类对象
	import {
		msgHomeData,
		msgChatData
	} from '@/object/msg.js'

	//5，引入网络请求
	import {
		queryGroupByHeadInfo,
		queryGroupUsers
	} from '@/api/http/msg/group.js'
	import {
		queryUserIsRob,
		rob
	} from '@/api/http/msg/redpkg.js'


	export default {
		components: {
			myChat,
			chatRedpkgAnimation
		},
		data() {
			return {
				//我的信息
				userId: uni.getStorageSync('userId'),
				head: uni.getStorageSync('head'),
				nickname: uni.getStorageSync('nickname'),
				myNickname: uni.getStorageSync('nickname'),

				friendName: '', //群聊名称
				msgObjectData: {}, //聊天对象信息
				groupInfo: '', //群聊信息

				allChatList: [], //所有的聊天信息
				chatList: [], //聊天主要信息
				chatImgs: [], //图片信息

				//禁言
				isShowSend: false,
				//是否能发送消息
				isCanSend: true,
				//底部输入框按钮
				sendTitle: '群聊禁言',

				pageSize: 20,
				pageNum: 1,
				total: 0,

				//红包信息
				showHbMsg: {},
				isShowHb: false,
				openbrnanimation: {}, //红包点击动画
				openrbagmodelshow: false,

				//语音播放
				innerAudioContent: uni.createInnerAudioContext(),
				isChangeBottom: true, // 默认滚动到最底部

			}
		},
		computed: {
			...mapState('m_chat', ['chatData', 'topMsgData', 'notTopMsgData']),
			...mapGetters('m_chat', ['getChatData']),
		},
		watch: {
			chatData() {
				//console.log(123123412)
			},
			topMsgData() {
				//console.log(123)
				//版本1
				// this.chatList = []
				// this.chatImgs = []
				// this.pageNum = 1
				// this.getChatList(1)
				// this.msgReag(this.msgObjectData)
				// this.gotoScrollBottom(30)

				//版本2
				/* var newMsg = this.topMsgData[0]
				if (newMsg.type == 3 && newMsg.id == this.msgObjectData.id) {
					this.chatList = []
					this.chatImgs = []
					var pageAllSize = this.pageSize * this.pageNum
					this.pageNum = 1
					this.pageSize = pageAllSize + 1
					this.getChatList(1)
					this.msgReag(this.msgObjectData)
					//获取最后一条
					var lastMsg = this.chatList[this.chatList.length - 1]

					// if (lastMsg.msgType == 21) {
					// 	return
					// }

					//console.log(lastMsg.sendId)
					if (lastMsg.sendId == this.userId) {
						this.gotoScrollBottom(30)
					} else {
						this.gotoScrollBottom(30, false)
					}*/

				//版本3
				var newMsg = this.notTopMsgData[0]
				if (newMsg.type == 3 && newMsg.id == this.msgObjectData.id) {
					// this.getChatByPageList()
					// return
					if (this.isChangeBottom) {
						this.chatList = []
						this.chatImgs = []
						this.pageNum = 1
						this.pageSize = 20
						this.getChatList(1)
						this.msgReag(this.msgObjectData)
						//获取最后一条
						var lastMsg = this.chatList[this.chatList.length - 1]
						if (lastMsg.sendId == this.userId) {
							this.gotoScrollBottom(30)
						} else {
							this.gotoScrollBottom(30, false)
							//this.$refs.myChatRef.showNewTips()
						}

					} else {
						this.chatList = []
						this.chatImgs = []
						//当前查询条数
						var pageAllSize = this.pageSize * this.pageNum
						this.pageNum = 1
						this.pageSize = pageAllSize + 1
						this.getChatList(1)
						this.msgReag(this.msgObjectData)
						//获取最后一条
						var lastMsg = this.chatList[this.chatList.length - 1]

						// if (lastMsg.msgType == 21) {
						// 	return
						// }

						if (lastMsg.sendId == this.userId) {
							this.gotoScrollBottom(30)
						} else {
							this.gotoScrollBottom(30, false)
							//this.$refs.myChatRef.showNewTips()
						}
					}
				}

			},
			notTopMsgData() {
				//console.log(this.notTopMsgData[0])
				var newMsg = this.notTopMsgData[0]
				if (newMsg.type == 3 && newMsg.id == this.msgObjectData.id) {
					// this.getChatByPageList()
					// return
					if (this.isChangeBottom) {
						this.chatList = []
						this.chatImgs = []
						this.pageNum = 1
						this.pageSize = 20
						this.getChatList(1)
						this.msgReag(this.msgObjectData)
						//获取最后一条
						var lastMsg = this.chatList[this.chatList.length - 1]
						if (lastMsg.sendId == this.userId) {
							this.gotoScrollBottom(30)
						} else {
							this.gotoScrollBottom(30, false)
							//this.$refs.myChatRef.showNewTips()
						}

					} else {
						this.chatList = []
						this.chatImgs = []
						//当前查询条数
						var pageAllSize = this.pageSize * this.pageNum
						this.pageNum = 1
						this.pageSize = pageAllSize + 1
						this.getChatList(1)
						this.msgReag(this.msgObjectData)
						//获取最后一条
						var lastMsg = this.chatList[this.chatList.length - 1]

						// if (lastMsg.msgType == 21) {
						// 	return
						// }

						if (lastMsg.sendId == this.userId) {
							this.gotoScrollBottom(30)
						} else {
							this.gotoScrollBottom(30, false)
							//this.$refs.myChatRef.showNewTips()
						}
					}


				}

				//console.log(123)

			}
		},
		methods: {
			...mapActions('m_chat', ['setMsgList', 'msgReag', 'msgGoTop', 'clearMsgByList', 'addChatData',
				'readRedPkgStore', 'removeMsvById'
			]),

			//1，查询指定页面数据
			getChatList(page, isgotoBottom = false) {
				for (var i = 0; i < this.chatData.length; i++) {
					if (this.chatData[i].id == this.msgObjectData.id && this.chatData[i].type == this.msgObjectData
						.type) {
						//1，计算出 总共能分成多少页
						var msgListLength = Math.ceil(this.chatData[i].list.length / this.pageSize)

						//2，如果要查看的页数大于总共分成的页数 或者 和该对象历史聊天数为0，返回没有更多数据可查
						if (page > msgListLength || this.chatData[i].list.length == 0) {
							console.log('没有消息')
							continue;
						}

						//3，获取 指定页数开始查询的list下标（如需要查询第2页 则从下标为10的数据开始往后查10个数据）
						var forPage = (page - 1) * this.pageSize
						for (forPage; forPage < (this.pageSize * page); forPage++) {
							//4，如果 总长度，大于 递增下标，则可以添加数据进行展示（如果小于或等于，代表没有更多顺序，直接返回就可以了）
							if (this.chatData[i].list.length > forPage) {
								//  && this.chatData[i].list[forPage].msgType != 21
								//将消息组装
								this.chatList.unshift(this.chatData[i].list[forPage])

								//判断消息类型是否为图片
								if (this.chatData[i].list[forPage].msgType == 2) {
									console.log(this.chatData[i].list[forPage].news)
									this.chatImgs.unshift(this.chatData[i].list[forPage].news)
								}

								//this.gotoScrollBottom(150)
							} else {
								continue;
							}
						}

						/* if (isgotoBottom) {
							this.gotoScrollBottom(100)
						} */
					}
				}
			},
			//1.1，查询页面聊天消息
			getChatByPageList() {
				//1，遍历所有的聊天信息
				for (var i = 0; i < this.chatData.length; i++) {
					if (this.chatData[i].id == this.msgObjectData.id &&
						this.chatData[i].type == this.msgObjectData.type) {
						//2，获取当前聊天的总聊天信息
						var newChatData = this.chatData[i].list

						if (newChatData.length == 0) {
							console.log('没有消息')
							return
						}

						//3，查询第一页的数据
						var onePageData = newChatData.slice(this.pageNum, this.pageNum + this.pageSize)
						for (var j = 0; j < onePageData.length; j++) {
							//3，判断消息类型是否为图片
							if (onePageData[j].msgType == 2) {
								this.chatImgs.unshift(onePageData[j].news)
							}
						}
						//4，给展示的列表赋值
						this.chatList = onePageData.concat(this.chatList)

						// this.chatList.unshift(onePageData)
						break;
					}
				}

			},

			//1.2，加载更多信息
			getChatListByPage() {
				/* this.pageNum = this.pageNum + this.pageSize
				this.getChatByPageList() */
				this.pageNum++
				this.getChatList(this.pageNum)

				setTimeout(() => {
					// uni.stopPullDownRefresh()
					this.$refs.myChatRef.closeRefreshScroll()
				}, 500)
			},
			//1.3，是否滚动到最底部
			changeMsgListLeng(isChange) {
				this.isChangeBottom = isChange
			},

			//2，查询聊天对象信息
			queryGroupByHeadInfo(fid) {
				queryGroupByHeadInfo(parseInt(fid), this.userId).then(res => {
					if (res.data.pubInfo.code !== 0) {
						if (res.data.pubInfo.message == '群聊已解散' || res.data.pubInfo.message == '未建立关系') {
							//开启禁言框
							this.isShowSend = true
							//不能发送
							this.isCanSend = false
							//设置禁言标语
							this.sendTitle = '已退出群聊'
							return;
						}
					}
					//2.3，参数保存
					var busInfo = res.data.busInfo

					this.friendName = busInfo.groupName
					this.groupInfo = busInfo
					//我在群聊中的备注
					if (busInfo.iInGroupRemarks) {
						this.nickname = busInfo.iInGroupRemarks
					}

					wx.setNavigationBarTitle({
						title: busInfo.groupName
					})
					//console.log(busInfo.identity)
					//判断是否禁言
					if (busInfo.estoppel == '1') {
						//判断用户身份
						if (busInfo.identity != '1' && busInfo.identity != '2') {
							//开启禁言框
							this.isShowSend = true
						}
					}
				})
			},

			//3，发送文本消息消息
			sendMsg(data) {
				//console.log(data)
				this.socketSendMsg(data, 0)
			},
			//4，消息滚动到底部
			gotoScrollBottom(time = 50, isSendMsg = true) {
				//console.log(123)
				this.$refs.myChatRef.initScrollBar(time, isSendMsg)
			},

			//5，跳转好友设置页面
			gotoUserSet(item) {
				if (this.groupInfo.protect == '1' && this.groupInfo.identity == '3') {
					//开启保护模式
					console.log('目前为群保护模式！')
					return;
				}

				if (item.sendId == this.userId) {
					//用户点击自己的头像
					return;
				}

				var req = {
					id: item.sendId,
					nickname: item.sendNickname,
					head: item.sendHead,
					type: 2, //用户群聊
				}

				uni.navigateTo({
					url: '/subpkg/msg/user/user-describe/user-describe?msgObject=' + JSON.stringify(req),
				})
			},

			//6，红包相关
			//6.1，点击红包消息
			showRedPkg(item) {
				//判断是否实名认证 如果没有实名认证无法下单
				if (!uni.getStorageSync('identifyCheck')) {
					return uni.$showMsg('请先进行实名认证！')
				}
				//console.log(item)
				//this.isShowHb = true
				this.showHbMsg = item
				if (!item.isRedRead) {
					var req = item
					req.type = 3
					req.id = this.msgObjectData.id
					//红包已读
					this.readRedPkgStore(req)
				}

				//console.log(item)
				//如果是专属红包无法零钱
				var newMsg = JSON.parse(item.news)
				if (newMsg.hbType == '3') {
					if (item.sendId == this.userId) {
						//跳转到详情页面
						var redPkgMsgInfo = {
							redPkgId: item.redPkgId,
							identity: this.groupInfo.identity,
							protect: this.groupInfo.protect
						}
						return uni.navigateTo({
							url: '/subpkg/msg/red-pkg/red-pkg-group/red-pkg-group?redPkgMsgInfo=' +
								JSON
								.stringify(redPkgMsgInfo)
						});
					} else {
						if (newMsg.appointUserId != this.userId) {
							//不是指定对象，无法领取
							return uni.$showMsg('您无权领取！');
						}
					}
				}
				queryUserIsRob(item.redPkgId).then(res => {
					if (res.data.pubInfo.code !== 0) {
						//该用户已经抢过红包或是红包已经抢完
						//return uni.$showMsg(res.data.pubInfo.message);

						var redPkgMsgInfo = {
							redPkgId: item.redPkgId,
							identity: this.groupInfo.identity,
							protect: this.groupInfo.protect
						}

						return uni.navigateTo({
							url: '/subpkg/msg/red-pkg/red-pkg-group/red-pkg-group?redPkgMsgInfo=' +
								JSON
								.stringify(redPkgMsgInfo)
						})
					}
					//还有剩余红包，可以抢
					this.isShowHb = true
				})
			},
			//6.2，关闭红包
			closeHbFun() {
				this.isShowHb = false
			},
			//6.3，开始抢红包
			openHbFun(item) {
				var that = this;
				var animation = uni.createAnimation({
					duration: 1000,
					timingFunction: 'ease',
				})
				that.openbrnanimation = animation;
				// animation.rotate3d(0,1,0,360).step();
				animation.rotateY(360).step();
				that.openbrnanimation = animation.export();

				console.log(item)
				rob(item.redPkgId, this.userId, this.nickname).then(res => {
					if (res.data.pubInfo.code !== 0) {
						//该用户已经抢过红包或是红包已经抢完
						uni.$showMsg(res.data.pubInfo.message);
					} else {
						//抢到了红包，发送消息
						//sendId, sendName, redPkgId, robId, robName
						//console.log(JSON.parse(item.news).hbType)

						var robHbMsgInfo = {
							sendId: item.sendId,
							sendName: item.sendNickname,
							redPkgId: item.redPkgId,
							robId: that.userId,
							robName: that.myNickname,
							robAmount: res.data.busInfo.robAmount,
							title: res.data.busInfo.title,
							surplusAmount: res.data.busInfo.surplusAmount,
							totalAmount: res.data.busInfo.totalAmount,
							totalNum: res.data.busInfo.totalNum,
							generateArr: res.data.busInfo.generateArr,
							readUserIds: res.data.busInfo.readUserIds,
							maxIndex: res.data.busInfo.maxIndex,
							maxAmount: res.data.busInfo.maxAmount,
							type: res.data.busInfo.type,
							readUserNames: res.data.busInfo.readUserNames,
							hbType: JSON.parse(item.news).hbType
						}
						//robHbMsg()
						var sendData = {
							types: 21, //消息类型 （0文本，1图片连接，2音频，3地图）
							msg: JSON.stringify(robHbMsgInfo)
						}
						that.socketSendMsg(sendData)
					}

					//console.log(res.data.busInfo)
					that.isShowHb = false
					//that.rbagmodelshow = false;
					that.openrbagmodelshow = true;
					that.openbrnanimation = {};

					var redPkgMsgInfo = {
						redPkgId: item.redPkgId,
						identity: this.groupInfo.identity,
						protect: this.groupInfo.protect
					}

					return uni.navigateTo({
						url: '/subpkg/msg/red-pkg/red-pkg-group/red-pkg-group?redPkgMsgInfo=' + JSON
							.stringify(redPkgMsgInfo)
					})
				})
			},
			//6.4，查看红包
			gotoDetail(item) {
				var redPkgMsgInfo = {
					redPkgId: item.redPkgId,
					identity: this.groupInfo.identity,
					protect: this.groupInfo.protect
				}

				return uni.navigateTo({
					url: '/subpkg/msg/red-pkg/red-pkg-group/red-pkg-group?redPkgMsgInfo=' + JSON
						.stringify(redPkgMsgInfo)
				})
			},

			//7，删除消息
			closeUserMsg(showPopChatItem) {
				//删除消息
				for (var i = 0; i < this.chatList.length; i++) {
					if (this.chatList[i].msgId == showPopChatItem.msgId) {
						this.chatList.splice(i, 1)
						continue;
					}
				}
				this.removeMsvById(showPopChatItem)
				return
			},

			//8，撤回消息
			withdrawUserMsg(showPopChatItem) {
				let data = {
					msg: '撤回一条消息',
					types: 11
				}
				this.socketSendMsg(data, showPopChatItem.msgId)
			},

			//10，语音播放
			handleAudio(item) {
				this.innerAudioContent.paused ? this.playAudio(item) : this.stopAudio(item);

				this.innerAudioContent.onPlay(() => {
					//console.log('播放')
					//this.innerAudioContent.paused = false
				})

				this.innerAudioContent.onEnded(() => {
					//console.log('暂停播放')
					//this.innerAudioContent.paused = true
					this.stopAudio(item)
				})
			},
			//10.1，播放音频
			playAudio(item) {
				//console.log(item)
				var voice = JSON.parse(item.news)
				var voiceUrl = voice.voice
				this.innerAudioContent.src = voiceUrl
				this.innerAudioContent.play()

				for (var i = 0; i < this.chatList.length; i++) {
					if (this.chatList[i].msgId == item.msgId && this.chatList[i].time == item.time) {
						var oldVoice = JSON.parse(this.chatList[i].news)
						oldVoice.anmitionPlay = true
						this.chatList[i].news = JSON.stringify(oldVoice)
					}
				}

			},
			//10.2，停止音频
			stopAudio(item) {
				var voice = JSON.parse(item.news)
				this.innerAudioContent.src = ''
				this.innerAudioContent.stop()
				for (var i = 0; i < this.chatList.length; i++) {
					if (this.chatList[i].msgId == item.msgId && this.chatList[i].time == item.time) {
						var oldVoice = JSON.parse(this.chatList[i].news)
						oldVoice.anmitionPlay = false
						this.chatList[i].news = JSON.stringify(oldVoice)
					}
				}
			},

			//websocket
			//1，socket发送消息
			socketSendMsg(e, msgId) {
				if (!this.isCanSend) {
					console.log('群聊已解散')
					return
				}
				var that = this
				var nowTime = getNowTime() + ''

				//消息组装
				let msgData = {
					type: this.$chatType.CHAT_GROUP,
					msg: {
						id: msgId || 0,
						groupId: this.msgObjectData.id,
						senderId: this.userId,
						types: e.types, //消息类型 （0文本，1图片连接，2音频，3地图）
						message: e.msg, //消息 
						time: nowTime,
						groupHead: this.msgObjectData.head,
						groupName: this.msgObjectData.nickname,
						senderHead: this.head,
						senderName: this.myNickname,
						state: 0
					}
				}

				//console.log(msgData)
				var that = this
				uni.myWebsocket.socketTask.send({
					data: JSON.stringify(msgData),
					async success() {},
					fail(e) {
						uni.$showMsg('发送失败！');
						uni.myWebsocket.socketTask.close
						uni.myWebsocket = ''
						that.connectSocketInit()
					}
				});
			},
			//2，消息监听
			listenSocketMsg() {
				if (uni.myWebsocket == undefined || uni.myWebsocket == '' || uni.myWebsocket == null) {
					//连接上websocket
					uni.$connectSocketInit.connectSocket(uni.$nettyPort)
				}

				//消息监听
				var that = this
				uni.myWebsocket.socketTask.onMessage((result) => {
					var res = JSON.parse(result.data)

					if (res.type == uni.$chatType.CHAT_GROUP && res.params.groupId == that.msgObjectData.id) {
						//群聊禁言
						if (res.params.types == uni.$chatType.ESTOPPEL) {
							//console.log(res.params.message)
							//res.params.message.indexOf('开启') != -1 
							if (that.isContainStr(res.params.message, '开启')) {
								//判断用户身份
								if (that.groupInfo.identity != '1' && that.groupInfo.identity != '2') {
									//开启禁言框
									that.isShowSend = true
								}
							} else {
								that.isShowSend = false
							}

							//console.log(res.params.message)
							//that.queryGroupByHeadInfo(res.params.groupId, that.userId)
						} else if (res.params.types == uni.$chatType.PROTECT) {
							//console.log(res.params.message)
							// res.params.message.indexOf('开启') != -1 /
							if (that.isContainStr(res.params.message, '开启')) {
								//判断用户身份
								//console.log('测试1')
								that.groupInfo.protect = '1';
							} else {
								//console.log('测试2')
								that.groupInfo.protect = '2';
							}
						} else if (res.params.types == uni.$chatType.KICK_OUT_USER) {
							//踢出群聊
							var userId = JSON.parse(res.params.message).userId
							if (that.userId == userId) {
								//开启禁言框
								that.isShowSend = true
								//不能发送
								that.isCanSend = false
								//设置禁言标语
								that.sendTitle = '已退出群聊'
							}

						}
					} else if (res.type == uni.$chatType.DISSOLUTION_GROUP) {
						//群聊解散
						that.isCanSend = false
					}

				})

			},

			isContainStr(str1, str2) {
				if (str1 == null || str2 == null) {
					return false
				}
				return (str1.indexOf(str2) !== -1)
			}

		},
		onLoad(e) {
			var msgObject = JSON.parse(e.msgObject)
			//console.log(msgObject)
			this.msgObjectData = msgObject

			//消息已读
			this.msgReag(msgObject)

			//获取聊天对象信息
			this.queryGroupByHeadInfo(msgObject.id)

			wx.setNavigationBarTitle({
				title: msgObject.nickname
			})

			//消息监听
			this.listenSocketMsg()

		},
		onShow() {
			//消息已读
			this.msgReag(this.msgObjectData)
			this.listenSocketMsg()
		},
		mounted() {
			//获取第一页聊天信息
			this.getChatList(1, true)
			//this.getChatByPageList()
			this.gotoScrollBottom(30)
		},
		activated() {
			//this.gotoScrollBottom(50)
		},

		onNavigationBarButtonTap(e) {
			if (this.isCanSend) {
				return uni.navigateTo({
					url: '/subpkg/msg/set/set-group/set-group-main/set-group-main?msgObject=' + JSON.stringify(
						this.msgObjectData)
				})
			}
		},
		onHide() {
			console.log('隐藏')
			this.innerAudioContent.stop()
		},
		onBackPress() {
			console.log('隐藏2')
			this.innerAudioContent.stop()
		},
		onUnload() {
			console.log('隐藏3')
			this.innerAudioContent.stop()
		}
	}
</script>

<style>

</style>